package com.jy.oms.framework.asyn.task.queue.memory;

import com.jy.oms.framework.asyn.task.checker.model.ExecutorCheckResult;
import com.jy.oms.framework.asyn.task.constants.TaskStateEnum;
import com.jy.oms.framework.asyn.task.model.TaskDto;
import com.jy.oms.framework.asyn.task.model.TaskQueryDto;
import com.jy.oms.framework.asyn.task.model.TaskResultDto;
import com.jy.oms.framework.asyn.task.model.TaskWrapper;
import com.jy.oms.framework.asyn.task.queue.AbstractTaskQueueManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.DelayQueue;

@Service
public class MemoryTaskQueueManager extends AbstractTaskQueueManager {
    private static Logger logger = LoggerFactory.getLogger(MemoryTaskQueueManager.class);
    private ConcurrentMap<String, DelayQueue<DelayedTask>> queueMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, TaskWrapper> taskWrapperMap = new ConcurrentHashMap<>();

    @Override
    public void add(TaskWrapper taskWrapper) {
        super.add(taskWrapper);

        if (queueMap.get(taskWrapper.getTaskGroup()) == null) {
            queueMap.putIfAbsent(taskWrapper.getTaskGroup(), new DelayQueue<>());
        }

        TaskDto taskDto = taskWrapper.getTaskDto();
        if (StringUtils.isBlank(taskWrapper.getParamIdentifier())) {
            String taskParam = this.convertTaskParam(taskDto);
            String taskIdentifier = this.generateTaskIdentifier(taskDto.getTaskCode(), taskParam);
            taskWrapper.setParamIdentifier(taskIdentifier);
        }

        queueMap.get(taskWrapper.getTaskGroup()).put(new DelayedTask(taskWrapper.getParamIdentifier(), taskDto.getDelayedSeconds()));
        taskWrapperMap.putIfAbsent(taskWrapper.getParamIdentifier(), taskWrapper);
    }

    @Override
    public void addBatch(List<TaskWrapper> taskWrapperList) {
        for (TaskWrapper taskWrapper : taskWrapperList) {
            this.add(taskWrapper);
        }
    }

    @Override
    public List<TaskWrapper> poll(TaskQueryDto taskQueryDto) {
        DelayQueue<DelayedTask> delayQueue = queueMap.get(taskQueryDto.getTaskGroup());
        if (delayQueue == null) {
            return null;
        }

        List<TaskWrapper> taskWrapperList = new ArrayList<>();
        try {
            DelayedTask delayedTask = delayQueue.take();
            TaskWrapper taskWrapper = taskWrapperMap.remove(delayedTask.getTaskIdentifier());
            taskWrapperList.add(taskWrapper);
        } catch (InterruptedException e) {
            logger.warn("pop task error.", e);
        }

        return taskWrapperList;
    }

    @Override
    public void finish(TaskResultDto taskResultDto) {
        super.finish(taskResultDto);

        TaskWrapper taskWrapper = taskResultDto.getTaskWrapper();
        TaskDto taskDto = taskWrapper.getTaskDto();
        long delayedSeconds = 0;
        if (taskResultDto.isCheckFilter()) {
            ExecutorCheckResult executorCheckResult = taskResultDto.getExecutorCheckResult();
            if (executorCheckResult.getEarliestExecuteTime() != null) {
                long gap = executorCheckResult.getEarliestExecuteTime().getTime() - System.currentTimeMillis();
                delayedSeconds = (int) gap / 1000;
            } else if (TaskStateEnum.DONE == executorCheckResult.getTaskState()) {
                //do nothing
            } else {
                //检查不通过情况下，默认延时10分钟再次查询检查任务是否可执行
                delayedSeconds = 10 * 60;
            }
        } else if (taskResultDto.getTaskState() == TaskStateEnum.INVALID) {
            //无效任务延时1天
            delayedSeconds = 24 * 60 * 60;
        } else if (taskResultDto.getTaskState() == TaskStateEnum.TIMEOUT) {
            //超时任务延时30分钟(超时并不是没执行成功，延时时间不能小于[TaskRunningStateCollector]运行状态过期时间)
            delayedSeconds = 30 * 60;

            this.alarmTimeoutTask(taskResultDto);
        } else if (taskResultDto.isEnableRetry()) {
            //重试任务
            delayedSeconds = taskResultDto.getRetryIntervalSeconds();
        }

        taskWrapper.setCallCount(taskResultDto.getCallCount());
        if (delayedSeconds > 0) {
            //任务重进入队列
            taskDto.setDelayedSeconds(delayedSeconds);
            this.add(taskWrapper);
        }
    }

    @Override
    public void finish(List<TaskResultDto> taskResultList) {
        for (TaskResultDto taskResultDto : taskResultList) {
            this.finish(taskResultDto);
        }
    }

    @Override
    public void remove(TaskWrapper taskWrapper) {
        TaskDto taskDto = taskWrapper.getTaskDto();
        DelayQueue<DelayedTask> delayQueue = queueMap.get(taskWrapper.getTaskGroup());
        if (delayQueue == null) {
            return;
        }

        String taskParam = this.convertTaskParam(taskDto);
        String taskIdentifier = this.generateTaskIdentifier(taskDto.getTaskCode(), taskParam);
        delayQueue.remove(taskIdentifier);
        taskWrapperMap.remove(taskIdentifier);
    }
}
